<template>
  <el-dialog
    v-model="dialogVisible"
    title="Import Questions"
    width="50%"
    :before-close="handleClose"
    class="import-dialog"
  >
    <div class="dialog-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else>
        <div class="import-options">
          <h4>Select Import Options</h4>
          
          <el-form :model="importOptions" label-position="top">
            <el-form-item label="Import Destination">
              <el-radio-group v-model="importOptions.destination">
                <el-radio label="new_exercise">Create New Exercise</el-radio>
                <el-radio label="existing_exercise">Add to Existing Exercise</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item v-if="importOptions.destination === 'existing_exercise'" label="Select Exercise">
              <el-select v-model="importOptions.exerciseId" placeholder="Select an exercise" style="width: 100%">
                <el-option
                  v-for="exercise in exercises"
                  :key="exercise.id"
                  :label="exercise.title"
                  :value="exercise.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="Questions to Import">
              <el-checkbox v-model="importOptions.selectAll" @change="handleSelectAllChange">
                Select All ({{ totalQuestions }} questions)
              </el-checkbox>
              
              <div class="questions-list">
                <el-checkbox-group v-model="importOptions.selectedQuestions">
                  <div v-for="question in questions" :key="question.id" class="question-item">
                    <el-checkbox :label="question.id">
                      <div class="question-preview">
                        <span class="question-text">{{ truncateText(question.text, 80) }}</span>
                        <el-tag size="small" :type="getQuestionTypeColor(question.type)">
                          {{ formatQuestionType(question.type) }}
                        </el-tag>
                      </div>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleImport" :disabled="!canImport" :loading="importing">
          Import
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ImportDialog',
  
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    document: {
      type: Object,
      default: null
    }
  },
  
  emits: ['update:modelValue', 'import-complete'],
  
  setup(props, { emit }) {
    const loading = ref(false)
    const importing = ref(false)
    const questions = ref([])
    const exercises = ref([])
    
    const importOptions = ref({
      destination: 'new_exercise',
      exerciseId: null,
      selectAll: false,
      selectedQuestions: []
    })
    
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })
    
    const totalQuestions = computed(() => questions.value.length)
    
    const canImport = computed(() => {
      if (importOptions.value.selectedQuestions.length === 0) {
        return false
      }
      
      if (importOptions.value.destination === 'existing_exercise' && !importOptions.value.exerciseId) {
        return false
      }
      
      return true
    })
    
    const handleClose = () => {
      dialogVisible.value = false
    }
    
    const fetchData = async () => {
      if (!props.document) return
      
      loading.value = true
      
      try {
        // In a real application, you would fetch questions and exercises from an API
        // const questionsResponse = await api.getDocumentQuestions(props.document.id)
        // const exercisesResponse = await api.getExercises()
        // questions.value = questionsResponse.data
        // exercises.value = exercisesResponse.data
        
        // Mock data for demonstration
        setTimeout(() => {
          questions.value = [
            {
              id: 1,
              text: 'What is the main purpose of the document?',
              type: 'open_ended',
              difficulty: 2
            },
            {
              id: 2,
              text: 'Which of the following statements is true according to the document?',
              type: 'multiple_choice',
              difficulty: 1,
              options: [
                'Option A',
                'Option B',
                'Option C',
                'Option D'
              ],
              correctAnswer: 1
            },
            {
              id: 3,
              text: 'Explain the relationship between concepts X and Y mentioned in section 3.',
              type: 'open_ended',
              difficulty: 3
            }
          ]
          
          exercises.value = [
            {
              id: 1,
              title: 'JavaScript Basics'
            },
            {
              id: 2,
              title: 'Vue.js Components'
            },
            {
              id: 3,
              title: 'CSS Flexbox'
            }
          ]
          
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('Error fetching data:', error)
        ElMessage.error('Failed to load data')
        loading.value = false
      }
    }
    
    const handleSelectAllChange = (value) => {
      if (value) {
        importOptions.value.selectedQuestions = questions.value.map(q => q.id)
      } else {
        importOptions.value.selectedQuestions = []
      }
    }
    
    const handleImport = async () => {
      if (!canImport.value) return
      
      importing.value = true
      
      try {
        // In a real application, you would call an API to import questions
        // const payload = {
        //   documentId: props.document.id,
        //   destination: importOptions.value.destination,
        //   exerciseId: importOptions.value.exerciseId,
        //   questionIds: importOptions.value.selectedQuestions
        // }
        // await api.importQuestions(payload)
        
        // Mock successful import
        setTimeout(() => {
          ElMessage.success('Questions imported successfully')
          importing.value = false
          
          // Emit event to parent component
          emit('import-complete', {
            destination: importOptions.value.destination,
            exerciseId: importOptions.value.exerciseId,
            questionIds: importOptions.value.selectedQuestions
          })
          
          // Close dialog
          dialogVisible.value = false
        }, 1500)
      } catch (error) {
        console.error('Error importing questions:', error)
        ElMessage.error('Failed to import questions')
        importing.value = false
      }
    }
    
    const truncateText = (text, maxLength) => {
      if (!text) return ''
      if (text.length <= maxLength) return text
      return text.substring(0, maxLength) + '...'
    }
    
    const getQuestionTypeColor = (type) => {
      switch (type) {
        case 'multiple_choice':
          return 'success'
        case 'true_false':
          return 'warning'
        case 'open_ended':
          return 'info'
        default:
          return 'default'
      }
    }
    
    const formatQuestionType = (type) => {
      switch (type) {
        case 'multiple_choice':
          return 'Multiple Choice'
        case 'true_false':
          return 'True/False'
        case 'open_ended':
          return 'Open Ended'
        default:
          return type
      }
    }
    
    // Watch for dialog visibility
    watch(() => dialogVisible.value, (isVisible) => {
      if (isVisible) {
        // Reset form when dialog opens
        importOptions.value = {
          destination: 'new_exercise',
          exerciseId: null,
          selectAll: false,
          selectedQuestions: []
        }
        
        fetchData()
      }
    })
    
    return {
      dialogVisible,
      loading,
      importing,
      questions,
      exercises,
      importOptions,
      totalQuestions,
      canImport,
      handleClose,
      handleSelectAllChange,
      handleImport,
      truncateText,
      getQuestionTypeColor,
      formatQuestionType
    }
  }
}
</script>

<style scoped>
.import-dialog {
  max-width: 800px;
}

.dialog-content {
  min-height: 300px;
}

.loading-container {
  padding: 20px;
}

.import-options {
  padding: 0 10px;
}

.import-options h4 {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--el-text-color-primary);
}

.questions-list {
  max-height: 300px;
  overflow-y: auto;
  margin-top: 10px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  padding: 10px;
}

.question-item {
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.question-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.question-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-left: 8px;
}

.question-text {
  flex: 1;
  white-space: normal;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 